package kr.co.handysoft.common.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;

import kr.co.handysoft.common.profiler.IServerCommandHandler;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;

public class ServerCommandHandler extends Thread{

	private Socket socket;
	private Document doc;

	public ServerCommandHandler(Socket accept, Document doc) {
		this.socket = accept;
		this.doc = doc;
	}

	
	@Override
	public void run() {
		super.run();
		try {
			
			InputStream is = this.socket.getInputStream();
			OutputStream os = this.socket.getOutputStream();
			BufferedReader bufferR = new BufferedReader(new InputStreamReader(is));
			BufferedWriter bufferW = new BufferedWriter(new OutputStreamWriter(os));
			String commandResult = processFileHandler(bufferR.readLine().trim());
			if (commandResult == null){
				commandResult = "FAIL";
			}
			bufferW.write(commandResult +"\r\n");
			bufferW.flush();
			bufferW.close();
			bufferR.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (JDOMException e) {
			e.printStackTrace();
		}
	}


	private String processFileHandler(String trim) throws ClassNotFoundException, InstantiationException, IllegalAccessException, JDOMException {
		String command = trim.trim();
		Object cmdObj = XPath.selectSingleNode(doc,  "//command[@id='"+command+"']");
		
		if (cmdObj == null){
			return null;
		}else{
			Element cmdElement = (Element)cmdObj;
			Class<?> tmpClass = Class.forName(cmdElement.getAttributeValue("class"));
			Object tmpObject = tmpClass.newInstance();
			IServerCommandHandler cmdHandler = (IServerCommandHandler)tmpObject;
			return new CommunicationData((IServerCommandHandler)tmpObject).toJSON();
		}
	}

}
